#include "../../afwApp.h"
#include "windowsfix.h"
#include "cstring.h"

using namespace one_rag::App::impl;

Win32Window::Win32Window():_hwnd(0)
{
}

Win32Window::~Win32Window()
{
}

bool Win32Window::Create(const char* name, ePositionType pos, int w, int h)
{
  DWORD styleEx = 0;
  DWORD style = WS_OVERLAPPEDWINDOW;
  HINSTANCE hInstance=0;
  LPCWSTR className = L"FRAMEWND";
  // Try and get the current hInstance
  //BOOL f = GetModuleHandleExW( GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT|GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,(LPCTSTR)&Win32Window::SWindowProc,&hInstance);
  //assert(f);

  CString titleString = name;

  WNDCLASSEXW wc = {0};
  wc.cbSize = sizeof(wc);

  ATOM atm = GetClassInfoExW(hInstance,className,&wc);
  if(!atm){
    wc.lpfnWndProc = SWindowProc;
    wc.hInstance = hInstance;
    atm = RegisterClassExW(&wc);
  }

  int x = CW_USEDEFAULT;
  int y = 0;
  w = CW_USEDEFAULT;
  h = 0;

  HMENU hMenu = 0;
  HWND hWndParent = 0;


  if(pos)
  {
    switch(pos){
      default:
      case windowPosDefault:
      x = y = CW_USEDEFAULT; break;
      case windowPosCenter:
      x=1024;y=768; break;
    }
  }

  _hwnd = CreateWindowExW(styleEx,titleString,(LPCWSTR)atm,style,x,y,w,h,hWndParent, hMenu, hInstance,this );

  ShowWindow(_hwnd,SW_SHOWDEFAULT);
  UpdateWindow(_hwnd);

  return true;
}

// static
LRESULT CALLBACK Win32Window::SWindowProc(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam){
  Win32Window* self=0;

  if(uMsg == WM_CREATE){
    LPCREATESTRUCT lpcs = (LPCREATESTRUCTW)lParam;
    self = (Win32Window*)lpcs->lpCreateParams;
    SetWindowLongPtrW(hWnd,GWLP_USERDATA,(LONG_PTR)self );
  }
  else {
    self = (Win32Window*)GetWindowLongPtrW(hWnd,GWLP_USERDATA);
  }

  return DefWindowProc(hWnd,uMsg,wParam,lParam);
}

// virtual
LRESULT Win32Window::WindowProc(UINT uMsg,WPARAM wParam,LPARAM lParam)
{
  return DefWindowProc(_hwnd,uMsg,wParam,lParam);
}

